package com.qupeng.demo.kafka.kafkaspringbootproducer.producer;

import com.qupeng.demo.kafka.kafkaspringbootproducer.config.KafkaProperties;
import com.qupeng.demo.kafka.kafkaspringbootproducer.model.CommonResponse;
import com.qupeng.demo.kafka.kafkaspringbootproducer.model.ProduceSuccessResponse;
import com.qupeng.demo.kafka.kafkaspringbootproducer.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/messages")
public class KafkaController {

    @Autowired
    private KafkaService<Integer, String> kafkaService;

    @Autowired
    private KafkaService<Integer, Product> kafkaServiceProduct;

    @Autowired
    private KafkaAdmin kafkaAdmin;

    @Autowired
    private KafkaProperties kafkaProperties;

    @PostMapping("")
    public CommonResponse<ProduceSuccessResponse<Integer, String>> produce(@RequestBody String messagePayload) {
        try {
            SendResult<Integer, String> sendResult = kafkaService.sendToKafkaSync(kafkaProperties.getTopics().get(0), RandomNumberGenerator.getRandom(100), messagePayload);
            return new CommonResponse<>("producer", new ProduceSuccessResponse<Integer, String>((sendResult)));
        } catch (ExecutionException | InterruptedException e) {
            return new CommonResponse<>("001-producer-controller", e.getMessage(), "producer");
        }
    }

    @PostMapping("/products")
    public CommonResponse<ProduceSuccessResponse<Integer, Product>> produce(@RequestBody Product product) {
        try {
            SendResult<Integer, Product> sendResult = kafkaServiceProduct.sendToKafkaSync(kafkaProperties.getTopics().get(0), RandomNumberGenerator.getRandom(100), product);
            return new CommonResponse<>("producer", new ProduceSuccessResponse<Integer, Product>((sendResult)));
        } catch (ExecutionException | InterruptedException e) {
            return new CommonResponse<>("002-producer-controller", e.getMessage(), "producer");
        }
    }
}
